package org.springblade.modules.door.task;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.extern.slf4j.Slf4j;
import org.springblade.modules.door.emus.DoorConstant;
import org.springblade.modules.door.entity.DoorDevice;
import org.springblade.modules.door.mapper.DoorDeviceMapper;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Slf4j
@Component
@ConditionalOnProperty(name ="task.enable", havingValue = "true",matchIfMissing = true)
public class DoorDeviceTask {

	@Resource
	private DoorDeviceMapper doorDeviceMapper;


		@Async("coffeeTaskExecutor")
		@Scheduled(cron = "0 0/10 * * * *")
		public void doorState() {
			DateTime dateTime = DateUtil.offsetMinute(new Date(), -30);
			LambdaQueryWrapper<DoorDevice> deviceWrapper = Wrappers.lambdaQuery();
			deviceWrapper.le(DoorDevice::getHeartTime, dateTime);
			deviceWrapper.eq(DoorDevice::getDeviceState, DoorConstant.DeviceState.ON);
			List<DoorDevice> doorDevices = doorDeviceMapper.selectList(deviceWrapper);
			for (DoorDevice doorDevice : doorDevices) {
				LambdaUpdateWrapper<DoorDevice> updateWrapper = Wrappers.lambdaUpdate();
				updateWrapper.eq(DoorDevice::getDeviceCode, doorDevice.getDeviceCode());
				updateWrapper.set(DoorDevice::getDeviceState, DoorConstant.DeviceState.OFF);
				doorDeviceMapper.update(null, updateWrapper);
				log.info("door设备离线变更{}===>{}",doorDevice.getDeviceCode(),doorDevice.getHeartTime());

			}
		}
}
